import 'package:audioplayers/audioplayers.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

import '../../../dd_core/dd_log_service.dart';
import '../../../dd_core/dd_other.dart';
import '../../../dd_models/dd_hive_comment_model.dart';
import '../../../dd_models/dd_hive_works_model.dart';
import '../../../r.dart';
import '../../dd_home/controllers/dd_comment_controller.dart';
import '../../dd_home/pages/dd_comment_page.dart';
import '../../dd_personal_center/views/dd_view_background.dart';
import '../controllers/dd_video_palyer_controller.dart';

class DDVideoScreen extends StatefulWidget {
  final HiveWorksModel model;
  const DDVideoScreen({super.key, required this.model});

  @override
  _DDVideoScreenState createState() => _DDVideoScreenState();
}

class _DDVideoScreenState extends State<DDVideoScreen> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    var uri = Uri.parse(widget.model.mediaUrl ?? '');
    _controller = VideoPlayerController.networkUrl(
      uri,
    )..initialize().then((_) {
        setState(() {});
        _controller.play();
      });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DDVideoPlayerController>(
        init: DDVideoPlayerController(widget.model),
        initState: (state) {
          DDLogService().ddGa(page: "video_player");
        },
        dispose: (state) {},
        builder: (videoPlayerController) {
          return Obx(() => Scaffold(
                backgroundColor: Colors.black,
                body: SafeArea(
                  top: false,
                  bottom: false,
                  child: GestureDetector(
                    onTap: () {
                      _controller.value.isPlaying
                          ? _controller.pause()
                          : _controller.play();
                    },
                    child: Stack(
                      children: [
                        Positioned.fill(
                          child: _controller.value.isInitialized
                              ? FittedBox(
                                  fit: BoxFit.cover,
                                  child: SizedBox(
                                    width: _controller.value.size.width,
                                    height: _controller.value.size.height,
                                    child: VideoPlayer(_controller),
                                  ),
                                )
                              : Center(
                                  child: CircularProgressIndicator(),
                                ),
                        ),
                        Positioned(
                          top: 50,
                          left: 0,
                          right: 16,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              IconButton(
                                icon: Image.asset(R.assetsImagesVideo4),
                                onPressed: () {
                                  Get.back();
                                },
                              ),
                              SizedBox(
                                width: 4,
                              ),
                              ClipRRect(
                                borderRadius: BorderRadius.circular(18),
                                child: CachedNetworkImage(
                                  width: 36,
                                  height: 36,
                                  imageUrl: videoPlayerController
                                          .userModelObx.value.avatarUrl ??
                                      '',
                                  placeholder: (context, url) => Placeholder(),
                                  errorWidget: (context, url, error) =>
                                      Placeholder(),
                                ),
                              ),
                              SizedBox(
                                width: 8,
                              ),
                              Text(
                                'Nickname',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 14),
                              ),
                              IconButton(
                                icon: videoPlayerController
                                            .userModelObx.value.myFollow ??
                                        false
                                    ? Image.asset(R.assetsImagesHome7)
                                    : Image.asset(R.assetsImagesHome15),
                                onPressed: () {
                                  videoPlayerController.updateFollow();
                                },
                              ),
                              Spacer(),
                              IconButton(
                                icon: Image.asset(
                                  R.assetsImagesHomeSecond2,
                                  height: 36,
                                  width: 36,
                                  fit: BoxFit.cover,
                                ),
                                onPressed: () {
                                  _showBottomSheet(
                                      context, videoPlayerController);
                                },
                              ),
                            ],
                          ),
                        ),
                        Positioned(
                          bottom: 40,
                          left: 16,
                          right: 16,
                          child: Container(
                            height: MediaQuery.of(context).size.height * 0.38,
                            child: ListView.builder(
                              // reverse: true,
                              shrinkWrap: false,
                              controller:
                                  videoPlayerController.scrollController,
                              itemBuilder: (context, index) {
                                return VideoCommentItem(
                                    model: videoPlayerController
                                        .messageList[index]);
                              },
                              itemCount:
                                  videoPlayerController.messageList.length,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                floatingActionButton: SizedBox(
                  width: 38.0,
                  height: 38.0,
                  child: FloatingActionButton(
                    onPressed: () {
                      showModalBottomSheet(
                        context: context,
                        isScrollControlled: true,
                        builder: (context) => Container(
                          child: DDCommentPage(
                            model: widget.model,
                            onlyText: false,
                            commentController: Get.put(DDCommentController()),
                          ),
                        ),
                      );
                    },
                    child: Image.asset(
                      R.assetsImagesVideo5,
                    ),
                  ),
                ),
              ));
        });
  }

  void _showBottomSheet(
      BuildContext context, DDVideoPlayerController _controller) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16.0)),
      ),
      builder: (BuildContext context) {
        return SafeArea(
            child: Container(
          padding: EdgeInsets.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              ListTile(
                title: Center(
                    child: Text(
                        _controller.userModelObx.value.myFollow ?? false
                            ? 'Unfollow'
                            : 'Follow',
                        style: TextStyle(fontSize: 16))),
                onTap: () {
                  // Add your follow action here
                  Navigator.pop(context);
                  _controller.updateFollow();
                },
              ),
              ListTile(
                title: Center(
                    child: Text('Block', style: TextStyle(fontSize: 16))),
                onTap: () {
                  // Add your block action here
                  Navigator.pop(context);
                  _controller.updateBlock();
                },
              ),
              ListTile(
                title: Center(
                    child: Text('Report', style: TextStyle(fontSize: 16))),
                onTap: () {
                  // Add your report action here
                  Navigator.pop(context);
                  _showBottomSheet1(context, _controller);
                },
              ),
              SizedBox(height: 16),
              DDViewBackGround(
                content: Container(
                  width: 183,
                  height: 44,
                  child: DDSafeButton(
                    // padding: EdgeInsets.only(top: 20, bottom: 20),
                    child: Text(
                      "Cancel",
                      style: TextStyle(fontSize: 16, color: Color(0xff53BFD7)),
                    ),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ),
              ),
            ],
          ),
        ));
      },
    );
  }

  void _showBottomSheet1(
      BuildContext context, DDVideoPlayerController controller) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16.0)),
      ),
      builder: (BuildContext context) {
        return SafeArea(
            child: Container(
          padding: EdgeInsets.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              ListTile(
                title: Center(
                    child:
                        Text('Pornographic', style: TextStyle(fontSize: 16))),
                onTap: () {
                  Navigator.pop(context);
                  //_showSnackBar("Report Successfully", context);
                  controller.report('Pornographic');
                },
              ),
              ListTile(
                title: Center(
                    child:
                        Text('False gender', style: TextStyle(fontSize: 16))),
                onTap: () {
                  // Add your block action here
                  Navigator.pop(context);
                  controller.report('False gender');
                },
              ),
              ListTile(
                title: Center(
                    child: Text('Fraud', style: TextStyle(fontSize: 16))),
                onTap: () {
                  // Add your report action here
                  Navigator.pop(context);
                  controller.report('Fraud');
                },
              ),
              ListTile(
                title: Center(
                    child: Text('Political sensitive',
                        style: TextStyle(fontSize: 16))),
                onTap: () {
                  // Add your report action here
                  Navigator.pop(context);
                  controller.report('Political sensitive');
                },
              ),
              ListTile(
                title: Center(
                    child: Text('Other', style: TextStyle(fontSize: 16))),
                onTap: () {
                  // Add your report action here
                  Navigator.pop(context);
                  controller.report('Other');
                },
              ),
              SizedBox(height: 16),
              DDViewBackGround(
                content: Container(
                  width: 183,
                  height: 44,
                  child: DDSafeButton(
                    // padding: EdgeInsets.only(top: 20, bottom: 20),
                    child: Text(
                      "Cancel",
                      style: TextStyle(fontSize: 16, color: Color(0xff53BFD7)),
                    ),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ),
              ),

              // TextButton(
              //   onPressed: () {
              //     Navigator.pop(context);
              //   },
              //   child: Text('Cancel', style: TextStyle(fontSize: 18, color: Colors.blue)),
              // ),
            ],
          ),
        ));
      },
    );
  }

  void _showSnackBar(String message, BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
      ),
    );
  }
}

class VideoCommentItem extends StatefulWidget {
  final HiveCommentModel model;
  final Function()? onClick;
  const VideoCommentItem({Key? key, required this.model, this.onClick})
      : super(key: key);

  @override
  State<VideoCommentItem> createState() => _VideoCommentItemState();
}

class _VideoCommentItemState extends State<VideoCommentItem> {
  final AudioPlayer audioPlayer = AudioPlayer();

  bool _isPlaying = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Future<void> dispose() async {
    audioPlayer.dispose();
    super.dispose();
  }

  Future<void> play() async {
    if (_isPlaying) {
      await audioPlayer.stop();
    } else {
      await audioPlayer.play(DeviceFileSource(widget.model.message ?? ''));
    }
    _isPlaying = !_isPlaying;
  }

  Future<void> pause() async {
    await audioPlayer.pause();
  }

  Future<void> stop() async {
    await audioPlayer.stop();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 20, right: 25, top: 10, bottom: 10),
      padding: EdgeInsets.only(left: 4, right: 12, top: 4, bottom: 4),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4.0),
        color: Color(0x4D000000),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(16.0),
            child: CachedNetworkImage(
              width: 32,
              height: 32,
              imageUrl: widget.model.iconUrl ?? '',
              placeholder: (context, url) => Placeholder(),
              errorWidget: (context, url, error) => Placeholder(),
            ),
          ),
          SizedBox(width: 8),
          widget.model.type == 2
              ? Padding(
                  padding:
                      EdgeInsets.only(left: 0, right: 0, top: 0, bottom: 0),
                  child: DDSafeButton(
                    onPressed: () {
                      play();
                    },
                    child: Container(
                      width: 80,
                      height: 28,
                      decoration: BoxDecoration(
                        color: Color(0xff53BFD7).withOpacity(0.5),
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                      ),
                      child: Center(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(R.assetsImagesHome16),
                            SizedBox(width: 5),
                            Text(
                              "${widget.model.soundTime}s",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ))
              : Expanded(
                  child: Text(
                    widget.model.message ?? '',
                    textAlign: TextAlign.left,
                    style: TextStyle(fontSize: 15, color: Colors.white),
                  ),
                ),
        ],
      ),
    );
  }
}
